package dk.rafaelcouto.PhoneTone_Extractor;

import android.annotation.SuppressLint;
import android.content.*;
import android.media.*;
import java.io.*;
import java.util.*;
import java.math.*;
import android.os.*;
import android.os.Process;

@SuppressLint("NewApi")
public class PhoneToneProcessor extends Thread
{
    private static int BUFFSIZE = 0;
    private static final int CHANNEL = 2;
    protected static final short[] CONSTANTS;
    private static final int ENCODING = 2;
    private static final int ERROR_MSG = -1;
    private static final int FREQUENCY = 44100;
    private static String LOGPATH;
    private static final int MY_MSG = 1;
    private static final int SILENCE = 3;
    private static final int TIME_MSG = 2;
    private static boolean check_ok = false;
    private static char dialtone = '\0';
    private static final int fft_size = 256;
    protected static final short[] goertzel_freq;
    private static final int goertzel_size = 1785;
    private static int last_media;
    private static char last_tone;
    private static int media;
    private static int next_ready;
    private static int silence;
    private Ai ai;
    Complex[] db_buffer;
    Complex[] db_buffer2;
    Complex[] fft_buffer;
    Context mContext;
    private Handler mHandle;
    private volatile boolean mIsLogging;
    private volatile boolean mIsRunning;
    AudioRecord mRecordInstance;
    private FileWriter mSplLog;
    private int[] results;
    private int sensitivity;
    short[] tempBuffer;
    private boolean verify;
    
    static {
        CONSTANTS = new short[] { 27860, 26745, 25529, 24216, 19747, 16384, 12773, 8967, 21319, 29769, 32706, 32210, 31778, 31226, -1009, -12772, -22811, -30555 };
        goertzel_freq = new short[] { 697, 770, 852, 941, 1209, 1336, 1477, 1633 };
        PhoneToneProcessor.LOGPATH = "/sdcard/PhoneToneExtractor_";
        PhoneToneProcessor.dialtone = ' ';
        PhoneToneProcessor.check_ok = false;
        PhoneToneProcessor.media = 0;
        PhoneToneProcessor.silence = 50;
        PhoneToneProcessor.last_media = PhoneToneProcessor.silence;
        PhoneToneProcessor.next_ready = 1;
    }
    
    public PhoneToneProcessor(final Handler mHandle, final Context mContext) {
        this.sensitivity = 250;
        this.ai = new Ai();
        this.results = new int[8];
        this.mIsRunning = false;
        this.mHandle = null;
        this.mSplLog = null;
        this.mIsLogging = false;
        this.tempBuffer = new short[2816];
        this.db_buffer = new Complex[256];
        this.db_buffer2 = new Complex[256];
        this.fft_buffer = new Complex[256];
        this.verify = false;
        this.mRecordInstance = null;
        this.mContext = null;
        this.mHandle = mHandle;
        this.mContext = mContext;
        this.mIsLogging = false;
        this.mIsRunning = false;
        BUFFSIZE = AudioRecord.getMinBufferSize(44100,
        		AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        this.mRecordInstance = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, 2, 2, PhoneToneProcessor.BUFFSIZE);
        this.start();
    }
    
    private void writeLog(final String s) {
        if (!this.mIsLogging) {
            return;
        }
        try {
            final Date date = new Date();
            (this.mSplLog = new FileWriter(String.valueOf(PhoneToneProcessor.LOGPATH) + date.getDate() + "_" + date.getMonth() + "_" + (1900 + date.getYear()) + ".xls", true)).append((CharSequence)(String.valueOf(date.getHours()) + ":" + date.getMinutes() + ":" + date.getSeconds() + " - " + s + "\n"));
            this.mSplLog.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public boolean get_verify() {
        return this.verify;
    }
    
    public double round(final double n, final int n2) {
        return new BigDecimal(Double.toString(n)).setScale(n2, 4).doubleValue();
    }
    
    @Override
    public void run() {
        while (true) {
            while (true) {
                try {
                    Process.setThreadPriority(-19);
                    while (!this.mIsRunning) {
                        this.mRecordInstance.stop();
                        if (!this.mIsRunning) {
                            if (this.mRecordInstance != null) {
                                this.mRecordInstance.stop();
                            }
                            Thread.sleep(300L);
                        }
                    }
                }
                catch (Exception ex) {
                    ex.printStackTrace();
                    this.mHandle.sendMessage(this.mHandle.obtainMessage(-1, (Object)new StringBuilder(String.valueOf(ex.getLocalizedMessage())).toString()));
                    if (this.mRecordInstance != null) {
                        this.mRecordInstance.release();
                        this.mRecordInstance = null;
                    }
                    return;
                }
                final long currentTimeMillis = System.currentTimeMillis();
                this.mRecordInstance.startRecording();
                this.mRecordInstance.read(this.tempBuffer, 0, 1785);
                final long n = System.currentTimeMillis() - currentTimeMillis;
                final Goertzel2 goertzel2 = new Goertzel2(44100.0f, 1785);
                int n2 = 0;
                final short[] goertzel_freq = PhoneToneProcessor.goertzel_freq;
                for (int length = goertzel_freq.length, i = 0; i < length; ++i) {
                    goertzel2.initGoertzel(goertzel_freq[i]);
                    this.results[n2] = (int)Math.sqrt(goertzel2.processSamples(this.tempBuffer));
                    ++n2;
                }
                PhoneToneProcessor.dialtone = this.ai.decide2(this.sensitivity, this.results);
                if (PhoneToneProcessor.dialtone == 'S') {
                    this.mHandle.sendMessage(this.mHandle.obtainMessage(2, (Object)n));
                    continue;
                }
                if (!this.verify) {
                    PhoneToneProcessor.last_tone = PhoneToneProcessor.dialtone;
                }
                PhoneToneProcessor.next_ready = 1;
                if (PhoneToneProcessor.dialtone != ' ' && PhoneToneProcessor.next_ready == 1 && PhoneToneProcessor.last_tone == PhoneToneProcessor.dialtone) {
                    PhoneToneProcessor.next_ready = 0;
                    PhoneToneProcessor.check_ok = true;
                }
                else {
                    PhoneToneProcessor.check_ok = false;
                }
                PhoneToneProcessor.last_tone = PhoneToneProcessor.dialtone;
                if (PhoneToneProcessor.check_ok) {
                    this.mHandle.sendMessage(this.mHandle.obtainMessage(1, (Object)PhoneToneProcessor.dialtone));
                    PhoneToneProcessor.last_media = PhoneToneProcessor.media;
                    PhoneToneProcessor.silence = PhoneToneProcessor.last_media;
                    continue;
                }
                this.mHandle.sendMessage(this.mHandle.obtainMessage(2, (Object)n));
                continue;
            }
        }
    }
    
    public void setSensitivity(final int sensitivity) {
        this.sensitivity = sensitivity;
    }
    
    public void set_verify(final boolean verify) {
        this.verify = verify;
    }
    
    public void startLogging() {
        this.mIsLogging = true;
    }
    
    public void start_engine() {
        this.mIsRunning = true;
    }
    
    public void stopLogging() {
        this.mIsLogging = false;
    }
    
    public void stop_engine() {
        this.mIsRunning = false;
        this.mRecordInstance.stop();
    }
}
